package cn.hist.hfp.service;

import cn.hist.hfp.entity.User;
import cn.hist.hfp.entity.UserValidation;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.UserRepository;
import cn.hist.hfp.repository.UserValidationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserValidationService {

    private final
    UserValidationRepository userValidationRepository;

    private final
    UserService userService;

    @Autowired
    public UserValidationService(UserValidationRepository userValidationRepository, UserService userService) {
        this.userValidationRepository = userValidationRepository;
        this.userService = userService;
    }

    public UserValidation findByUserId(int user_id) {
        User user = userService.findOne(user_id);

        Optional<UserValidation> optionalUserValidation = userValidationRepository.findTopByUser(user);
        if (optionalUserValidation.isPresent()) {
            return optionalUserValidation.get();
        }
        throw new ResourceNotFoundException();
    }

    public UserValidation save(UserValidation userValidation) {
        return userValidationRepository.save(userValidation);
    }

    public UserValidation update(UserValidation userValidation) {
        return userValidationRepository.save(userValidation);
    }

    public void delete(int user_id) {
        User user = userService.findOne(user_id);
        Optional<UserValidation> optionalUserValidation = userValidationRepository.findTopByUser(user);
        optionalUserValidation.ifPresent(userValidationRepository::delete);
    }
}
